package com.sz.common.pay.citic.xml;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.*;

/**
 * Created by siqishangshu on 17/10/10.
 * <p>
 * 封装了XML转换成object，object转换成XML的代码
 */
public class XmlMapper {

    /**
     * 将对象直接转换成String类型的 XML输出
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj) {
        StringWriter sw = new StringWriter();
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "CHARSET_GBK");
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(obj, sw);
        } catch (JAXBException e) {
            System.out.println("convert " + obj.getClass() + " to xml error " + e.getMessage());
            e.printStackTrace();
        }
        return XmlFormatUtil.toXml(sw.toString(), obj.getClass());
    }

    /**
     * 将String类型的xml转换成对象
     * //change the diff in citic xml
     */
    public static Object convertToObject(Class clazz, String xmlStr) {
        Object xmlObject = null;
        try {
            xmlStr = XmlFormatUtil.toObj(xmlStr, clazz);
            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(xmlStr);
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (JAXBException e) {
            System.out.println("convert xml  to " + clazz + " error " + e.getMessage());
            e.printStackTrace();
        }
        return xmlObject;
    }
}